<template>
    <div class="container">
        <div class="handle-box">
            <el-button @click="deleteAll">批量删除</el-button>
            <el-input v-model="searchWord" placeholder="筛选用户"></el-input>
        </div>

        <el-table height="550px" border size="small" :data="data" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="40" align="center"></el-table-column>
            <el-table-column label="ID" prop="id" width="50" align="center"></el-table-column>
            <el-table-column label="用户头像" width="102" align="center">
                <template v-slot="scope">
                    <img :src="attachImageUrl(scope.row.avator)" style="width: 80px" />
                </template>
            </el-table-column>
            <el-table-column label="用户名" prop="username" width="80" align="center"></el-table-column>
            <el-table-column label="性别" width="50" align="center">
                <template v-slot="scope">
                    <div>{{ changeSex(scope.row.sex) }}</div>
                </template>
            </el-table-column>
            <el-table-column label="手机号码" prop="phoneNum" width="120" align="center"></el-table-column>
            <el-table-column label="邮箱" prop="email" width="120" align="center"></el-table-column>
            <el-table-column label="生日" width="120" align="center">
                <template v-slot="scope">
                    <div>{{ getBirth(scope.row.birth) }}</div>
                </template>
            </el-table-column>
            <el-table-column label="签名" prop="introduction"></el-table-column>
            <el-table-column label="地区" prop="location" width="70" align="center"></el-table-column>
            <el-table-column label="收藏" width="90" align="center">
                <template v-slot="scope">
                    <el-button @click="goCollectPage(scope.row.id)">收藏</el-button>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="90" align="center">
                <template v-slot="scope">
                    <el-button type="danger" @click="deleteRow(scope.row.id)">删除</el-button>
                </template>
            </el-table-column>
            <el-table-column label="修改" width="90" align="center">

                <template v-slot="scope">
                    <el-upload :action="'http://localhost:8888/user/avatar/update?id=' + scope.row.id"
                        :show-file-list="false" :on-success="handleAvatarSuccess">
                        <!-- :before-upload="beforeAvatarUpload" -->
                        <el-button>更新头像</el-button>
                    </el-upload>
                </template>


            </el-table-column>
        </el-table>
        <el-pagination class="pagination" background layout="total, prev, pager, next" :current-page="currentPage"
            :page-size="pageSize" :total="tableData.length" @current-change="handleCurrentChange">
        </el-pagination>
    </div>

    <!-- 删除提示框 -->
    <yin-del-dialog :delVisible="delVisible" @confirm="confirm" @cancelRow="delVisible = $event"></yin-del-dialog>
</template>

<script lang="ts">
import { defineComponent, getCurrentInstance, watch, ref, reactive, computed } from "vue";
import mixin from "@/mixins/mixin";
import { HttpManager } from "@/api";
import { RouterName } from "@/enums";
import YinDelDialog from "@/components/dialog/YinDelDialog.vue";
import { getBirth } from "@/utils";

export default defineComponent({
    components: {
        YinDelDialog,
    },
    setup() {
        const { proxy } = getCurrentInstance();
        const { changeSex, routerManager } = mixin();

        const tableData = ref([]); // 记录歌曲，用于显示
        const tempDate = ref([]); // 记录歌曲，用于搜索时能临时记录一份歌曲列表
        const pageSize = ref(5); // 页数
        const currentPage = ref(1); // 当前页

        // 计算当前表格中的数据
        const data = computed(() => {
            return tableData.value.slice((currentPage.value - 1) * pageSize.value, currentPage.value * pageSize.value);
        });

        const searchWord = ref(""); // 记录输入框输入的内容
        watch(searchWord, () => {
            if (searchWord.value === "") {
                tableData.value = tempDate.value;
            } else {
                tableData.value = [];
                for (let item of tempDate.value) {
                    if (item.username.includes(searchWord.value)) {
                        tableData.value.push(item);
                    }
                }
            }
        });

        getUserData();

        // 获取用户信息
        async function getUserData() {
            tableData.value = [];
            tempDate.value = [];
            const result = (await HttpManager.getAllUser()) as ResponseBody;
            tableData.value = result.data;
            tempDate.value = result.data;
            currentPage.value = 1;
        }
        // 获取当前页
        function handleCurrentChange(val) {
            currentPage.value = val;
        }

        /**
         * 路由
         */
        function goCollectPage(id) {
            const breadcrumbList = reactive([
                {
                    path: RouterName.Consumer,
                    name: "用户管理",
                },
                {
                    path: "",
                    name: "收藏信息",
                },
            ]);
            proxy.$store.commit("setBreadcrumbList", breadcrumbList);
            routerManager(RouterName.Collect, { path: RouterName.Collect, query: { id } });
        }

        /**
         * 删除
         */
        const idx = ref(-1); // 记录当前要删除的行
        const multipleSelection = ref([]); // 记录当前要删除的列表
        const delVisible = ref(false); // 不显示删除框

        // 删除单个项
        async function deleteOne(id) {
            const result = (await HttpManager.deleteUser(id)) as ResponseBody;
            (proxy as any).$message({
                message: result.message,
                type: result.type,
            });
            if (result.code == 200) {
                getUserData();  // 更新数据，刷新用户列表
            }
        }

        // 确认删除（单个或批量）
        async function confirm() {
            if (idx.value !== -1) {
                await deleteOne(idx.value);  // 删除单个项
                idx.value = -1  // 重置下标
            } else {
                await confirmDeleteAll();  // 批量删除
            }
            delVisible.value = false;  // 隐藏删除对话框
        }

        // 删除按钮（弹出确认提示框）
        function deleteRow(id) {
            idx.value = id;
            delVisible.value = true;
        }

        // 处理选中项
        function handleSelectionChange(val) {
            multipleSelection.value = val;
        }

        // 删除所有选中项
        function deleteAll() {
            if (multipleSelection.value.length > 0) {
                // 执行批量删除
                delVisible.value = true;
            } else {
                alert('没有选中任何项！');
            }
        }

        // 确认删除所有选中的项
        async function confirmDeleteAll() {
            for (let item of multipleSelection.value) {
                await deleteOne(item.id);  // 删除每一项
            }
            // 删除成功后清空选择的项
            multipleSelection.value = [];
            (proxy as any).$message({
                message: '所有选中的项已成功删除',
                type: 'success',
            });
        }

        // 取消删除操作
        const cancelDeleteAll = () => {
            delVisible.value = false; // 只隐藏对话框
        };

        //handleAvatarSuccess
        function handleAvatarSuccess() {
            location.reload();
        }

        return {
            searchWord,
            data,
            tableData,
            delVisible,
            pageSize,
            currentPage,
            confirmDeleteAll,
            deleteAll,
            cancelDeleteAll,
            handleSelectionChange,
            handleCurrentChange,
            changeSex,
            getBirth,
            deleteRow,
            handleAvatarSuccess,
            confirm,
            goCollectPage,
            attachImageUrl: HttpManager.attachImageUrl,
        };
    },
});
</script>

<style scoped></style>
